<?php
/**
 * Created by PhpStorm.
 * User: huangzikun
 * Date: 2018/4/19
 * Time: 16:23
 */
namespace Huangzikun\hawkeye_spider;

class UploadClass
{
    const HTTP_SUCCESS = 1;
    const HTTP_FAIL = 0;

    public $upload = [];
    private $host = null;
    private $port = null;
    private $machineId = null;

    public function __construct()
    {
        //抓取配置文件
        $path = __DIR__ . "/../config/config.json";
        $config = file_get_contents($path) or die("can't find config!!!");
        $config = json_decode($config, true);
        //类映射配置
        $collMapping = include_once __DIR__ . "/../config/classMapping.php";
        $collection = $config['collection'];
        $this->host = $config['remote_host_ip'];
        $this->port = $config['remote_host_port'];
        $this->machineId = $config['machine_id'];

        if(!empty($collection) && is_array($collection)){
            foreach ($collection as $type){
                if($type['enable'] == true){
                    $class = new $collMapping[$type['type']]($type['api_address']);
                    if(!empty($type['special'])){
                        foreach ($type['special'] as $key => $value){
                            $class->$key = $value;
                        }
                    }
                    $this->upload[] = $class;
                }
            }
        }
    }

    public function grab()
    {
        if(!empty($this->upload)){
            foreach ($this->upload as $collection){
                $collection->grab();
                $this->curlPost(
                    $this->host,
                    $this->port,
                    $collection->apiAddress,
                    $collection->spiderInfo
                );
            }
        }
    }

    public function curlPost($host, $port, $api, $data)
    {
        if(empty($data)){
            return self::HTTP_FAIL;
        }
        $params = json_encode($data);
        $ch = curl_init();//初始化
        echo $params.PHP_EOL;
        $url = "http://{$host}:{$port}{$api}/{$this->machineId}";
        echo $url.PHP_EOL;
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ch, CURLOPT_POST, true);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
    }
}